/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			unfinishedButton.java
 * Description:	 	This is the class for which
 * 					is responsible for counting
 * 					the numbers of unfinished 
 * 					patients.
 * 
 * Responsible
 * =================================================
 * Name:			Jakob Sulby
 * Study number:	09136
 * 
 */
package dk.iha.toksEditor;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class unfinishedButton extends LinearLayout
{
	Button button;
	TextView value;
	Integer number = -1;
	
	public unfinishedButton(Context context, AttributeSet attrs) {
		super(context, attrs);

		String infService = Context.LAYOUT_INFLATER_SERVICE;
		LayoutInflater li;
		li = (LayoutInflater)getContext().getSystemService(infService);
		li.inflate(R.layout.unfinished_button_view, this, true);
		
		// Get references to the child controls.
		button = (Button)findViewById(R.id.unfinishedButtonLabel);
		value = (TextView)findViewById(R.id.unfinishedButtonValueField);
		value.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				updateContent();
				unfinishedButton.this.setVisibility(shouldBeEnabled());
			}
		});
		
		button.setText(R.string.mainUnfinishedPatientsButtonText);
		
		updateContent();		
	}

	/**
	 * Updates the value of the button
	 */
	public void updateContent()
	{
		DBAdapter localDB = new DBAdapter(getContext());
		
		localDB.open();
	    try 
	    {
	    	number = localDB.getPatientCount();
	    	if(number < 100)
	    		value.setText(number.toString());
	    	else
	    		value.setText("+99");
		} 
	    
	    catch (Exception e) 
	    {
	    	value.setText("?");
		}
	    
	    localDB.close();
	    this.setVisibility(shouldBeEnabled());
	}
	
	public int shouldBeEnabled()
	{
		try 
		{
			if(number <= 0)
				return View.GONE;
			
			else
				return View.VISIBLE;
		} 
		catch (Exception e) 
		{
			return View.GONE;
		}
	}
}
